package com.forg.mvc.core.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.forg.mvc.core.RequestContext;
import com.forg.mvc.core.RequestDispatcher;
import com.forg.mvc.core.common.Constant;
import com.forg.mvc.core.factory.RequestWraperFactory;
import com.forg.mvc.core.factory.ResponseWraperFactory;
import com.forg.mvc.core.plugin.PluginManger;

//@WebServlet(urlPatterns="*.do", loadOnStartup = 0)
@WebServlet(urlPatterns="/*", loadOnStartup = 0)
public class DispatcherServlet extends HttpServlet{

	private static final long serialVersionUID = -8248817109486350219L;

	Logger logger = LoggerFactory.getLogger(DispatcherServlet.class);
	
	RequestDispatcher dispatcher  = RequestDispatcher.getInstance();
	
	@Override
	public void init() throws ServletException {
		super.init();
		
		dispatcher.init();
		PluginManger.init();
	}



	
	/**
	 * 主入口
	 * http://local.com:8080/forgSimpleMVC/hello.do?t=123
	 * 
	 * uri=/forgSimpleMVC/hello.do
	 * url=http://local.com:8080/forgSimpleMVC/hello.do
	 * servletPath=/hello.do
	 */
	@Override
	protected void service(HttpServletRequest r, HttpServletResponse p) throws ServletException, IOException {

		r.setCharacterEncoding(Constant.DEFAULT_ENCODEING);
		
		RequestContext.setRequest(RequestWraperFactory.createRequest(r));
		RequestContext.setResponse(ResponseWraperFactory.createRequest(p));
		
		//分发请求
		dispatcher.dispatch();
	}

	
}
